﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using ElectrosLtd.Models;
using Utilities;
using System.Net;
using System.Net.Mail;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Common.Views;

namespace ElectrosLtd.Controllers
{
    public class FaultController : Controller
    {
        //
        // GET: /Fault/
        

        public ActionResult FaultSubmited()
        {
            return View();
        }

        public ActionResult WarrantyExpired()
        {
            return View();
        }

        public ActionResult SubmitFault(DateTime date)
        {
            if (DateTime.Now <= date)
            {
                return View(new FaultModel());
            }

            return RedirectToAction("WarrantyExpired");

        }

        [HttpPost]
        public ActionResult SubmitFault(Guid oID,int id, FaultModel fm)
        {
            Encryption e = new Encryption();

            //Decrypts token password and pin to get user password
            string passwordMatches = "";
            
            try
            {
                passwordMatches = e.DecryptTripleDES(fm.Password, fm.PIN.ToString());

                //Check whether the username and password exist and if the authentication is valid
                if (new UsersServ.WCFUsersClient().IsAuthenticationValid(fm.Username, passwordMatches))
                {
                    User thisU = new UsersServ.WCFUsersClient().GetUser(fm.Username);

                    //Creates instance of user fault
                    UserFault newUF = new UserFault();

                    //Sets details
                    newUF.Username_FK = fm.Username;
                    newUF.Product_FK = id;
                    newUF.Status_FK = 1;
                    newUF.Date = DateTime.Now;

                    if (fm.CategoryID > 0)
                    {
                        newUF.Category_FK = fm.CategoryID;
                    }

                    //Gets an array with 6 random numbers for ticket number
                    int[] ticketNo = new TicketingServ.WCFTicketingClient().GenerateTicketNumber();

                    int tn1 = ticketNo[0];
                    int tn2 = ticketNo[1];
                    int tn3 = ticketNo[2];
                    int tn4 = ticketNo[3];
                    int tn5 = ticketNo[4];
                    int tn6 = ticketNo[5];

                    //Passes number to tnt and then converts to int to set the instance FaultID
                    string tnt = tn1 + "" + tn2 + "" + tn3 + "" + tn4 + "" + tn5 + "" + tn6;
                    newUF.FaultID = Convert.ToInt32(tnt);

                    newUF.Details = fm.Details;

                    new UsersServ.WCFUsersClient().SubmitFault(newUF);

                    //Barcode Service
                    byte[] imgbyte = new BarcodeServ.BarCode().Code39(tnt, 10, true, "Userbarcode");
                    MemoryStream ms = new MemoryStream(imgbyte);
                    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

                    //Send Message to user
                    new MSGServ.WCFMessagingClient().SendSMS(thisU.MobileNumber);

                    //Sends Fault receipt by calling email method 
                    SendFaultReceipt(oID, id, tnt, img);

                    return RedirectToAction("FaultSubmited", "Fault");
                }
                else
                {
                    
                }
            }
            catch (Exception ex)
            {
                return RedirectToAction("FaultError", "Fault");
            }

            return RedirectToAction("MyOrders", "Home");
        }

        public void SendFaultReceipt(Guid oID, int pID, string tnt, System.Drawing.Image img)
        {
            List<UserOrderDetailsView> userOD = new UsersServ.WCFUsersClient().GetOrderDetailsByOrderIDandProductID(oID, pID).ToList();
            List<FaultDetailsView> userFD = new UsersServ.WCFUsersClient().GetFaultDetailsForPDF(HttpContext.User.Identity.Name, Convert.ToInt32(tnt)).ToList();
            
            //PDF 
            string contents = "";
            string date = DateTime.Now.ToShortDateString();
            date = date.Replace('/', '-');

            MemoryStream ms = new MemoryStream();
            Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 30, 20);
            PdfWriter writer = PdfWriter.GetInstance(doc, ms);
            {
                doc.Open();
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(img, System.Drawing.Imaging.ImageFormat.Jpeg);
                doc.Add(image);
                                


                string FR = "Fault Receipt: " + tnt;
                
                contents += "<h1>Electros Ltd. " + date + "</h1>";

                contents += "<h2>Fault Receipt: </h2>" + tnt;

                contents += "<h3>Item(s): </h3>";
                contents += "<table>";
                contents += "<tr><b><th>Item </th><th>Amount Purchased </th><th>Date Purchased </th><th>Warranty Expiry Date </th><th>Price </th></tr>";

                string pName = "";
                int Quantity = 0;
                decimal Price = 0;
                DateTime OrderDate = DateTime.Now;
                DateTime ExpiryDate = DateTime.Now;
                string docCont = "";
                foreach (UserOrderDetailsView oudv in userOD)
                {
                    pName = oudv.ProductName;
                    Quantity = oudv.Quantity;
                    Price = oudv.Price * Quantity;
                    OrderDate = oudv.ExpiryDate;
                    ExpiryDate = oudv.ExpiryDate.AddYears(2);

                    contents += "<tr><td>" + pName + "</td><td>" + Quantity + " </td><td>" + OrderDate.ToShortDateString() + "</td><td>" + ExpiryDate.ToShortDateString() + " </td><td>" + Convert.ToDouble(Price * Quantity) + "</td></tr>";
                    docCont = "<tr><td>" + pName + "</td><td>" + Quantity + " </td><td>" + OrderDate.ToShortDateString() + "</td><td>" + ExpiryDate.ToShortDateString() + " </td><td>" + Convert.ToDouble(Price * Quantity) + "</td></tr>";
                }

                contents += "</table>";
                contents += "<br/>";

                contents += "<h3>Fault(s): </h3>";
                
                contents += "<table>";
                contents += "<tr><b><th>Ticket Number</th><th>Date</th><th>Fault Details</th><th>Status</th></tr>";

                int fID = 0;
                int ticketNo = 0;
                DateTime fDate = DateTime.Now;
                string status = "";
                string fDetails = "";

                foreach (FaultDetailsView fdv in userFD)
                {
                    fID = fdv.FaultID;
                    ticketNo = fdv.TicketNo;
                    fDate = fdv.Date;
                    status = fdv.Status;
                    fDetails = fdv.FaultDetails;
                }

                contents += "<tr><td>" + fID + "</td><td>" + ticketNo+ " </td><td>" + fDate.ToShortDateString() + "</td><td>" + fDetails + " </td><td>" + status + "</td></tr>";
                contents += "</table>";

                PdfPTable Toptable = new PdfPTable(2);
                PdfPCell Titlecell = new PdfPCell(new Phrase("Electros Ltd."));
                PdfPCell Datecell = new PdfPCell(new Phrase(date + " - " + date ));
                
                Titlecell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
                Datecell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT;

                Titlecell.BorderWidthRight = 0;
                Datecell.BorderWidthLeft = 0;

                Toptable.AddCell(Titlecell);
                Toptable.AddCell(Datecell);

                doc.Add(Toptable);

                doc.Add(new Paragraph(20, "\u00a0"));

                PdfPTable table = new PdfPTable(5);
                PdfPCell cell = new PdfPCell(new Phrase("Items: "));
                cell.BackgroundColor = Color.LIGHT_GRAY;
                cell.Colspan = 5;
                cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                table.AddCell(cell);
                table.AddCell("Item");
                table.AddCell("Amount Purchased");
                table.AddCell("Date Purchased");
                table.AddCell("Warranty Expiry Date");
                table.AddCell("Price");

                foreach (UserOrderDetailsView oudv in userOD)
                {
                    pName = oudv.ProductName;
                    Quantity = oudv.Quantity;
                    Price = oudv.Price * Quantity;
                    OrderDate = oudv.ExpiryDate;
                    ExpiryDate = oudv.ExpiryDate.AddYears(2);

                    table.AddCell(pName);
                    table.AddCell(Quantity.ToString());
                    table.AddCell(OrderDate.ToShortDateString().ToString());
                    table.AddCell(ExpiryDate.ToShortDateString().ToString());
                    table.AddCell(Price.ToString().TrimEnd('2'));
                }
                
                doc.Add(table);
                doc.Add(new Paragraph(20, "\u00a0"));

                PdfPTable Faulttable = new PdfPTable(4);
                PdfPCell Faultcell = new PdfPCell(new Phrase("Faults: "));
                Faultcell.Colspan = 5;
                Faultcell.BackgroundColor = Color.LIGHT_GRAY;
                Faultcell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                Faulttable.AddCell(Faultcell);
                Faulttable.AddCell("Ticket Number");
                Faulttable.AddCell("Date");
                Faulttable.AddCell("Details");
                Faulttable.AddCell("Status");

                foreach (FaultDetailsView fdv in userFD)
                {
                    fID = fdv.FaultID;
                    ticketNo = fdv.TicketNo;
                    fDate = fdv.Date;
                    status = fdv.Status;
                    fDetails = fdv.FaultDetails;

                    Faulttable.AddCell(ticketNo.ToString());
                    Faulttable.AddCell(fDate.ToShortDateString().ToString());
                    Faulttable.AddCell(fDetails);
                    Faulttable.AddCell(status);
                }

                doc.Add(Faulttable);
                                
                doc.Add(Chunk.NEWLINE);
                                
                writer.CloseStream = false;
                doc.Close();
                ms.Position = 0;

            }

            User thisUser = new UsersServ.WCFUsersClient().GetUser(HttpContext.User.Identity.Name);

            MailMessage mm = new MailMessage();
            mm.To.Add(thisUser.Email);
            mm.From = new MailAddress("no-reply@ElectrosLtd.com");
            mm.Attachments.Add(new Attachment(ms, "FaultReceipt.pdf"));
            mm.Subject = "Fault Receipt";

            mm.Body = "Hi," + " " + thisUser.Firstname + " " + thisUser.Lastname + "<br/><br/> You have reported the following fault. <br/>";
            
            mm.Body += contents;
            mm.Body += "<br/><br/>Electros Ltd. Management";
            mm.Body += "<br/><br/>Copyright © 2014 Electros Ltd. All Rights Reserved. <br/> Designated trademarks and brands are the property of their respective owners. <br/> Electros Ltd and the Electros Ltd logo are trademarks of Electros Ltd.";
            mm.IsBodyHtml = true;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential("tonixbox11@gmail.com", "proAnthony12");

            client.Send(mm);
            //Redirects to success page
            RedirectToAction("FaultSubmited");          
        }

    }
}
